﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LexLib.LexemNameSpace;
using System.Threading;
using TextEditor4.Parser;
using LexLib.LexerNameSpace;
using System.Diagnostics;
using System.Windows;
using TextEditor4.Refactoring;

namespace TextEditor4
{
    public partial class Rename_Form : Form
    {
        private Lexer myLex;
        private RichTextBox mainRTB;
       

        public Rename_Form(Lexer myLex, RichTextBox mainRTB, string s)
        {
            this.myLex = myLex;
            this.mainRTB = mainRTB;
            InitializeComponent();
            textBox2.Text = s;

          
        }

        private void Rename_Form_Load(object sender, EventArgs e)
        {

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //errorProvider1.SetError(this.textBox1, "Baga-baga");
            
            myLex.ArrOfLexems[0] = new Lexem(new ProgramType(), 0, myLex.ArrOfLexems[myLex.ArrOfLexems.Count - 1].EndIndex);
            Parser.Parser myP = new Parser.Parser(myLex.ArrOfLexems);
            TextEditor4.Parser.IParseNodeType tmp = myP.parse();
            int varNum = mainRTB.SelectionStart;
            
            Refactoring.Refactoring myR = new Refactoring.Refactoring(tmp, varNum);
            IParseNodeType refactedTree = myR.Refactor(tmp);
            List<int> myrefList = myR.refPositions;
            myrefList.Sort();
            myrefList.Reverse();
            if (myrefList.Count != 0)
            {
                changeNames(myrefList, getSize(varNum), textBox1.Text);
            }
            else 
            {
                ExceptionForm myEF = new ExceptionForm("There is no definition of this variable");
                myEF.Show();
            }
        }

        private void changeNames(List<int> placesToChange, int oldSize, string newName)
        {
            foreach (int i in placesToChange)
            {
                mainRTB.Select(i, oldSize);
                mainRTB.SelectedText = newName;
            }
        }
        private int getSize(int position)
        {
            for (int i = 1; i < myLex.ArrOfLexems.Count; i++)
            {
                if ((myLex.ArrOfLexems[i].BeginIndex <= position) && (myLex.ArrOfLexems[i].EndIndex > position))
                {
                    return (myLex.ArrOfLexems[i].EndIndex - myLex.ArrOfLexems[i].BeginIndex);
                }
            }
            return 0;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            
        }

     }
}
